#include "class_tick.h"

class_tick::class_tick(){}
class_tick::~class_tick(){}

//读入
int class_tick::read(std::string dz,int len)
{
struct_tick tick;
memset(&tick, 0, sizeof(struct_tick));
std::ifstream wj(dz.c_str(), std::ios::app | std::ios::binary | std::ios::ate | std::ios::in);

if(!wj.is_open() )
{
std::cout<<dz<<"打开失败"<<std::endl;
return 0;
}

std::streampos len1 = wj.tellg(),len2=len1;
if (len * sizeof(struct_tick) <len1)
{
len2 -= len * sizeof(struct_tick);
}
else {
len2 = 0;
}
wj.seekg(len2);

while (wj.tellg() + static_cast<std::streamoff>(sizeof(struct_tick)) < len1)
{
wj.read(reinterpret_cast<char *>(&tick), sizeof(struct_tick));

if(wj.fail() )
{
wj.clear();
std::cout<<dz<<"读取失败"<<std::endl;
break;
}

if(tick.UpdateTime[2] != ':' || tick.UpdateTime[5] != ':' )
{
len2 += 1;
wj.seekg(len2);
continue;
}
len2 += sizeof(struct_tick);
wj.seekg(len2);

lock.begin();
datas.push_back(tick);
lock.end();
}
wj.clear();
wj.close();
return datas.size();
}

//写出
int class_tick::write(std::string dz,int len)
{
if(datas.size() == 0)
{
return 0;
}

std::fstream wj;//声明写文件
wj.open(dz.c_str(), std::ios::app | std::ios::binary | std::ios::out);

if(!wj.is_open() )
{
	std::cout<<dz<<"打开失败"<<std::endl;
return 0;
}

for(int i=0;i<len;++i)
{
if(datas.size() == 0)
{
break;
}

lock.begin();
wj.write(reinterpret_cast<const char *>(&datas.front()), sizeof(struct_tick));
datas.pop_front();
lock.end();
}
wj.close();
datas.shrink_to_fit();

return 0;
}

//插入
void class_tick::insert(CThostFtdcDepthMarketDataField data)
{

struct_tick tick;

tick.LastPrice = data.LastPrice;
tick.BidPrice1=data.BidPrice1;
tick.AskPrice1=data.AskPrice1;
tick.OpenInterest=data.OpenInterest;
tick.Volume=data.Volume;
tick.BidVolume1=data.BidVolume1;
tick.AskVolume1=data.AskVolume1;
tick.UpdateMillisec=data.UpdateMillisec;
strncpy(tick.TradingDay,data.TradingDay, sizeof(tick.TradingDay));
strncpy(tick.UpdateTime,data.UpdateTime, sizeof(tick.UpdateTime));

lock.begin();
datas.push_back(tick);
lock.end();

return;
}
